<?php
declare (strict_types=1);

namespace app\admin\controller;

use app\BaseController;
use app\lib\exception\BaseException;
use app\model\Admins;
use app\model\ClassStudent;
use app\model\ClassTime;
use app\model\School;
use app\model\Ticket;
use app\model\Ticketuse;
use app\model\Useticket;
use think\Exception;
use think\facade\Db;

class Tickets extends BaseController
{
    public function index($limit = 10)
    {
        $name = request()->param('name');
        $status = request()->param('status');
        $time = request()->param('time');
        $data = Ticket::when($name, function ($query) use ($name) {
            $query->where('name', 'like', "%$name%");
        })->when($status, function ($query) use ($status) {
            $query->where('status', $status);
        })->when($time, function ($query) use ($time) {
            $query->whereBetween('create_time', $time);
        })->order('id', 'desc')->paginate($limit);
        return $this->success($data);
    }

    public function create()
    {
        $params = request()->param();
        $params['number'] = getNumber('套票');
        Ticket::create($params);
        return $this->success();
    }

    public function update($id)
    {
        Ticket::where('id', $id)->update(request()->param());
        return $this->success();
    }

    public function delete($id)
    {
        Ticket::where('id', 'in', $id)->delete();
        return $this->success();
    }


    /**
     * 获取学生套票
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getTickets($limit = 15)
    {
        $student = request()->param('student_id');

        $data = \app\model\InvoiceDetails::
              alias('ivd')
//            ->where('ivd.state', 0)
            ->join('invoice i', 'i.id=ivd.invoice_id')
            ->where('i.student_id', $student)
            ->where('ivd.type', 4)
            ->field('ivd.*,i.number')
            ->order('ivd.id', 'desc')
            ->paginate($limit)
            ->toArray();

        foreach ($data['data'] as $key=>&$item) {

            $item['useNum'] = Ticketuse::where('invoice_details_id', $item['id'])->where('student_id',$student)->sum('num');
            $course = Ticket::where('id', $item['cid'])->find()->toArray();
            $item['course'] = \app\model\Course::whereIn('id', $course['course_id'])->select()->toArray();
            $timestamp = strtotime($item['create_time']) + ($item['day']  * 24 * 60 * 60);
            $item['hereto']=  date('Y-m-d H:i:s', $timestamp);
            array_walk($item['course'], function (&$query) {
//                $query['teacher'] = implode(',', Admins::whereIn('id', $query['admins_id'])->column('name'));
                $query['teacher'] = Admins::whereIn('id', $query['admins_id'])->value('ename');
            });
            unset($item['ticket']);
//            if($item['useNum']>=$item['num']){
//                unset($data['data'][$key]);
//            }
        }

        return $this->success($data);
    }


    /**
     * 使用套票
     * @return \think\response\Json
     */
    public function useTickets()
    {
        $params = request()->param();
        Db::startTrans();

        try {
            foreach ($params['data'] as $item) {

                Ticketuse::create([
                    'invoice_details_id' => $item['invoice_id'],
                    'course_id' => $item['course_id'],
                    'student_id' => $params['student_id'],
                    'school_id' => $params['school_id'],
                    'num' => $item['num'],
                    'start_time' => $item['start_time'],
                    'end_time' => $item['end_time'] ?? '',
                ]);
                \app\model\InvoiceDetails::where('id', $item['invoice_id'])->update(['state' => 1]);
                $course = \app\model\Course::find($item['course_id']);

                $classTime = ClassTime::where('classroom_id', $course['classroom_id'])
                    ->where('admin_id', explode(',', $course['admins_id'])[0])
                    ->where('start_time', $item['start_time'])
                    ->where('end_time', $item['end_time'])
                    ->where('course_id', $item['course_id'])
                    ->find();

                if(empty($classTime)){
                    $classtime = ClassTime::create([
                        'admin_id' => explode(',', $course['admins_id'])[0],
                        'classroom_id' => $course['classroom_id'],
                        'course_id' => $item['course_id'],
                        'start_time' => $item['start_time'],
                        'end_time' => $item['end_time'],
                        'date' =>$item['date'],
                        'time1' =>$item['time1'],
                    ]);

                    ClassStudent::create([
                        'classtime_id' => $classtime->id,
                        'student_id' => $params['student_id'],
                        'invoice_details_id' => $item['invoice_id'],
                        'state'=>'末點名'
                    ]);
                }else{
                    $tab = ClassStudent::where('classtime_id', $classTime['id'])->where('student_id', $params['student_id'])->where('type', 1)->find();
                    if ($tab) { //需要判断是否已加入
                        $name = \app\model\Course::where('id', $item['course_id'])->value('name');

                        throw new Exception("該學生已經加入該時間段的課程，請勿重複操作");
                    }
                    ClassStudent::create([
                        'classtime_id' => $classTime['id'],
                        'student_id' => $params['student_id'],
                        'invoice_details_id' => $item['invoice_id'],
                        'state'=>'未點名'
                    ]);
                }

            }
            Db::commit();
            return $this->success();
        }catch (\Exception $e){
            Db::rollback();
            throw new BaseException(['msg'=>$e->getMessage()]);
        }

    }

    /**
     * 验证套票
     * @return bool
     */
    public function checkTickets()
    {
        $params = request()->param();
        foreach ($params['data'] as $item) {
            $course = \app\model\Course::find($item['course_id']);

            if (!empty($course)) {
                $class = ClassTime::where('classroom_id', $course['classroom_id'])
                    ->where('admin_id', explode(',', $course['admins_id'])[0])
                    ->where('start_time', $item['start_time'])
                    ->where('end_time', $item['end_time'])
                    ->where('course_id', $item['course_id'])
                    ->find();

                if ($class) {
                    $tab = ClassStudent::where('classtime_id', $class['id'])->where('student_id', $params['student_id'])->where('type', 1)->find();
                    if ($tab) { //需要判断是否已加入
                        $name = \app\model\Course::where('id', $item['course_id'])->value('name');
                        throw new BaseException(['msg' => "該學生已經加入該時間段的課程，請勿重複操作"]);
                    }
                } else {

                    //判断报名老师或教室是否被占用
                    $tab = $this->repeatedVerification(explode(',', $course['admins_id'])[0], $course['classroom_id'], $item['start_time'], $item['end_time'], $item['course_id'], $params['school_id']);

                    if ($tab) {
                        $name = School::where('id', $params['school_id'])->value('name');
                        throw new BaseException(['msg' => '在' . $name . '分校内的' . $item['start_time'] . '到' . $item['end_time'] . '時間段內選擇的老師或教室已被佔用，請重新規劃時間']);
                    }
                }
            }

        }
            return $this->success();
    }

    protected function repeatedVerification($admin_id, $classroom_id, $startTime, $endTime, $id = null, $school_id = null)
    {


        $start = ClassTime::alias('ct')
            ->join('class_student cs', 'cs.classtime_id = ct.id')
            ->join('invoice_details ind', 'ind.id = cs.invoice_details_id', 'left')
            ->join('invoice i', 'i.id = ind.invoice_id', 'left')
            ->join('student s', 'i.student_id = s.id', 'left')
            ->where('i.status', 1)
            ->where('ind.status', 1)
            ->where(function ($q) use ($school_id) {
                if ($school_id != null) {
                    $q->where('i.school_id', $school_id);
                }
            })
            ->where('ct.admin_id',$admin_id)
            ->where('ct.classroom_id',$classroom_id)
            ->where('ct.start_time',$startTime)
            ->where('ct.end_time',$endTime)
            ->where('ct.course_id','<>',$id)
            ->count();

        if($start){
            return true;
        }
            return false;

    }

}
